﻿using System.Drawing;
using System.Windows.Forms;

namespace Masuit.Tools.Form
{
    class Form
    {
        #region 窗体/控件 拖拽

        static Point mouseOff;//鼠标移动位置变量
        static bool Flag;//标签是否为左键
        /// <summary>
        /// 拖拽控制键设置，默认左键
        /// </summary>
        public static MouseButtons DragControlMouseButtons = MouseButtons.Left;

        private static void DragMouseDown(object sender, MouseEventArgs e)
        {

            if (e.Button == DragControlMouseButtons)
            {
                mouseOff = new Point(-e.X, -e.Y); //得到变量的值
                Flag = true;                  //点击按下时标注为true;
            }
        }

        private static void DragMouseMove(object sender, MouseEventArgs e)
        {
            Control control = sender as Control;
            if (Flag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(mouseOff.X, mouseOff.Y);  //设置移动后的位置
                if (control.Parent != null)
                {
                    mouseSet.Offset(-control.Parent.Location.X, -control.Parent.Location.Y);
                }
                control.Location = mouseSet;
            }
        }

        private static void DragMouseUp(object sender, MouseEventArgs e)
        {
            if (Flag)
            {
                Flag = false;//释放鼠标后标注为false;
            }
        }

        /// <summary>
        /// 设置控件/窗体 能够拖动
        /// </summary>
        /// <param name="control">需要设拖拽的控件</param>
        /// <param name="mouseButtons">默认左键拖拽</param>
        public static void DragSet(Control control)
        {
            control.MouseDown -= DragMouseDown;
            control.MouseMove -= DragMouseMove;
            control.MouseUp -= DragMouseUp;
            control.MouseDown += DragMouseDown;
            control.MouseMove += DragMouseMove;
            control.MouseUp += DragMouseUp;
        }

        #endregion
    }
}
